package com.szsh.aiot.hsm.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.util.Base64;

/**
 * @Description:
 * @Date 2023/10/27: 9:53
 * @Author: LOADING>>>>>
 */

public class AES {

    private static final int BLOCK_SIZE = 16;
    private static final byte[] INTERNAL_SECRET_KEY = new byte[]{1, 35, 69, 103, -119, -85, -51, -17, -2, -36, -70, -104, 118, 84, 50, 16};
    private static final byte[] SHARED_SECRET_KEY = new byte[]{1, 8, -49, -31, 77, 90, 10, 121, -14, 109, 107, 38, 29, 68, 59, 5};
    private static final String ALGORITHM = "AES";
    public static final String CIPHER_PADDING = "AES/ECB/PKCS5Padding";
    public static final String CIPHER_NOPADDING = "AES/ECB/NoPadding";
    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
    public static final AES INTERNAL_NOPADDING_AES;
    public static final AES INTERNAL_PADDING_AES;
    public static final AES SHARED_PADDING_AES;
    public static final AES SHARED_NOPADDING_AES;
    public static final AES DEFAULT_AES;
    private byte[] secretKey;
    private String cipherAlgorithm;
    private Charset charset;

    public AES(byte[] secretKey, String cipherAlgorithm) {
        this(secretKey, cipherAlgorithm, DEFAULT_CHARSET);
    }

    public AES(byte[] secretKey, String cipherAlgorithm, Charset charset) {
        this.secretKey = (byte[])secretKey.clone();
        this.cipherAlgorithm = cipherAlgorithm;
        this.charset = charset;
    }

    public byte[] decrypt(byte[] src) throws Exception {
        try {
            SecretKey deskey = new SecretKeySpec(this.secretKey, "AES");
            Cipher cipher = Cipher.getInstance(this.cipherAlgorithm);
            cipher.init(2, deskey);
            return cipher.doFinal(src);
        } catch (Exception var4) {
            throw new RuntimeException("AES Decrypt Exception , ", var4);
        }
    }


    private byte[] fixBytesBlock(byte[] src) {
        byte[] data = src;
        int len = src.length;
        int res = len % 16;
        if (res != 0) {
            data = new byte[len - res + 16];
            System.arraycopy(src, 0, data, 0, len);
        }

        return data;
    }
    static {
        INTERNAL_NOPADDING_AES = new AES(INTERNAL_SECRET_KEY, "AES/ECB/NoPadding");
        INTERNAL_PADDING_AES = new AES(INTERNAL_SECRET_KEY, "AES/ECB/PKCS5Padding");
        SHARED_PADDING_AES = new AES(SHARED_SECRET_KEY, "AES/ECB/PKCS5Padding");
        SHARED_NOPADDING_AES = new AES(SHARED_SECRET_KEY, "AES/ECB/NoPadding");
        DEFAULT_AES = INTERNAL_NOPADDING_AES;
    }
}
